<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/9/5
 * Time: 10:46
 */

namespace app\common\service;

use app\common\enum\StatusEnum;
use app\common\enum\TypeEnum;
use app\common\model\PBusiness;
use app\common\model\PChannelBankscope02 as PChannelBankscope02Model;
use app\common\model\SysBankList as SysBankListModel;
use app\common\model\PBusinessBankscope01 as PBusinessBankscope01Model;
use app\common\model\PBusinessBankscope02 as PBusinessBankscope02Model;
use think\Db;
use think\Exception;

class AllocationService
{
    /**
     * 分配资源
     * @param $param
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public static function allocation($param) {
        // 获取通道对应的可用资源记录
        $where = [
            'yxbz' => StatusEnum::RESOURCE_VALID,
            'channel' => $param['channel']
        ];
        $resource = PChannelBankscope02Model::all($where);

        $num = $param['num'];

        $business = PBusiness::get(['bcode' => $param['bcode']]);

        Db::startTrans();
        try {
            foreach ($resource as $v) {
                if ($v->num > $num) {
                    // todo 如果当前可用资源内的卡片数量大于分配数量
                    // 思路：将当前资源按分配数量拆成两块，新增两条记录，一条为已分配，另一条为未分配，删除当前资源，修改卡片数据

                    // 删除原资源
                    PChannelBankscope02Model::where('pc02id', '=', $v->pc02id)->delete();

                    $list = [
                        // 已分配记录数据
                        [
                            'pc02id' => Db::query("Call generate_serialno_copy('pc02id')")[0][0]['serialno'],
                            'allocation_no' =>  makeOrderNo(TypeEnum::ALLOCATION_NO_TYPE),
                            'channel' => $v->channel,
                            'start' => $v->start,
                            'end' => $v->start + $num - 1,
                            'bcode' => $param['bcode'],
                            'yxbz' => StatusEnum::RESOURCE_DISABLED,
                            'num' => $num,
                            'annual_fee' => $param['annual_fee'],
                            'annual_fee_expired' => date('Y-m-d'),
                            'annual_fee_total' => $num * $param['annual_fee']
                        ],
                        // 未分配记录数据
                        [
                            'pc02id' => Db::query("Call generate_serialno_copy('pc02id')")[0][0]['serialno'],
                            'allocation_no' => makeOrderNo(TypeEnum::ALLOCATION_NO_TYPE),
                            'channel' => $v->channel,
                            'start' => $v->start + $num,
                            'end' => $v->end,
                            'yxbz' => StatusEnum::RESOURCE_VALID,
                            'num' => $v->num - $num
                        ]
                    ];
                    (new PChannelBankscope02Model)->saveAll($list);

                    // 修改卡片数据
//                    SysBankListModel::updateCard($list[0]['start'], $list[0]['end'], $param, $list[0]['allocation_no']);

                    // 创建商户资源
                    self::createBusinessResource($v->channel, $list[0]['start'], $list[0]['end'], $param['bcode'], $business->b01id);

                    $num = 0; // 更新待分配数量为0
                    break;
                } elseif ($v->num == $num) {
                    // todo 如果当前可用资源内的卡片数量等于分配数量
                    // 将当前资源状态修改为已分配,更新下时间字段,关联目标商户,年费
                    $v->save([
                        'yxbz' => StatusEnum::RESOURCE_DISABLED,
                        'create_time' => date('Y-m-d H:i:s'),
                        'bcode' => $param['bcode'],
                        'annual_fee' => $param['annual_fee'],
                        'annual_fee_expired' => date('Y-m-d')
                    ]);
                    // 更新资源内的卡片信息
//                    SysBankListModel::updateCard($v->start, $v->end, $param, $v->allocation_no);

                    // 创建商户资源
                    self::createBusinessResource($v->channel, $v->start, $v->end, $param['bcode'], $business->b01id);

                    $num = 0; // 更新待分配数量为0
                    break;
                } elseif ($v->num >0) {
                    // todo 如果当前可用资源内的卡片数量少于分配数量,并且资源内卡片数量大于0
                    // 将当前资源状态修改为已分配,更新下时间字段,关联目标商户,年费
                    $v->save([
                        'yxbz' => StatusEnum::RESOURCE_DISABLED,
                        'create_time' => date('Y-m-d H:i:s'),
                        'bcode' => $param['bcode'],
                        'annual_fee' => $param['annual_fee'],
                        'annual_fee_expired' => date('Y-m-d')
                    ]);

                    // 更新资源内的卡片信息
//                    SysBankListModel::updateCard($v->start, $v->end, $param, $v->allocation_no);

                    // 创建商户资源
                    self::createBusinessResource($v->channel, $v->start, $v->end, $param['bcode'], $business->b01id);

                    $num -= $v->num; // 更新待分配数量减去相应的数量
                }
            }

            // 如果最终没有完全分配，抛出异常
            if ($num > 0) {
                throw new Exception('卡片数量不足，分配失败！');
            }

            Db::commit();
            return return_data('分配成功！');
        } catch (\Exception $e) {
            Db::rollback();
            return return_data($e->getMessage(), 1);
        }
        //
    }

    /**
     * 创建商家资源数据
     * @param $channel
     * @param $start
     * @param $end
     * @param $bcode
     * @param $b01id
     */
    public static function createBusinessResource($channel, $start, $end, $bcode, $b01id) {
        $business_resource_data = [
            'pbs01id' => Db::query("Call generate_serialno_copy('pbs01id')")[0][0]['serialno'],
            'pbs02id' => Db::query("Call generate_serialno_copy('pbs02id')")[0][0]['serialno'],
            'channel' => $channel,
            'start' => $start,
            'end' => $end,
            'bcode' => $bcode,
            'b01id' => $b01id,
        ];
        PBusinessBankscope01Model::create($business_resource_data, true);
        PBusinessBankscope02Model::create($business_resource_data, true);
    }
}